package com.greensam.pixelengine.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.greensam.pixelengine.config.CosClientConfig;
import com.greensam.pixelengine.constant.BaseConstant;
import com.greensam.pixelengine.exception.BusinessException;
import com.greensam.pixelengine.manager.CosManager;
import com.greensam.pixelengine.pojo.dto.picture.PictureUploadDto;
import com.greensam.pixelengine.pojo.emuns.ErrorCodeEnum;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * 图片上传模板
 *
 * @author Macro_Ray
 * @since 2025/7/19 10:55
 */
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    /**
     * 模板方法，定义上传流程
     *
     * @param inputSource      输入源
     * @param uploadPathPrefix 上传路径前缀
     * @return UploadPictureDto
     * @author Ma Chengrui
     * @since 2025/7/21
     */
    public final PictureUploadDto uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 校验图片
        validPicture(inputSource);

        // 图片上传地址
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(BaseConstant.DATE_PATTERN));
        String uuid = RandomUtil.randomString(12);
        String originFilename = getOriginFilename(inputSource);
        String uploadFilename = String.format("%s_%s.%s", date, uuid, FileUtil.getSuffix(originFilename));
        String uploadPath = String.format("/%s/%s/%s", BaseConstant.LOGO, uploadPathPrefix, uploadFilename);

        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 处理文件来源（本地或URL）
            processFile(inputSource, file);

            // 上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (!CollectionUtils.isEmpty(objectList)) {
                // 压缩图对象
                CIObject compressedCiObject = objectList.get(0);
                // 缩略图对象 默认为压缩图，只有生成缩略图才获取缩略图
                CIObject thumbnailCiObject = compressedCiObject;
                if (objectList.size() > 1) {
                    thumbnailCiObject = objectList.get(1);
                }
                // 封装处理后的图片返回结果
                return buildResult(originFilename, compressedCiObject, thumbnailCiObject, imageInfo);
            }
            // 封装原图返回结果
            return buildResult(originFilename, file, uploadPath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCodeEnum.FileUploadError);
        } finally {
            // 清理临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 校验输入源（本地文件或url）
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 封装压缩图返回结果
     *
     * @param originFilename     文件名
     * @param compressedCiObject 压缩图对象
     * @param thumbnailCiObject  缩略图对象
     * @param imageInfo          图片信息对象
     * @return UploadPictureDto
     * @author Ma Chengrui
     * @since 2025/7/21
     */
    private PictureUploadDto buildResult(String originFilename, CIObject compressedCiObject, CIObject thumbnailCiObject, ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round((double) picWidth / picHeight, 2).doubleValue();

        // 构造结果
        PictureUploadDto pictureUploadDto = new PictureUploadDto();
        pictureUploadDto.setName(FileUtil.mainName(originFilename));
        pictureUploadDto.setPicSize(compressedCiObject.getSize().longValue());
        pictureUploadDto.setPicWidth(picWidth);
        pictureUploadDto.setPicHeight(picHeight);
        pictureUploadDto.setPicScale(picScale);
        pictureUploadDto.setPicFormat(compressedCiObject.getFormat());
        // 图片主色调
        pictureUploadDto.setPicColor(imageInfo.getAve());
        // 设置图片为压缩后的地址
        pictureUploadDto.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        // 设置缩略图地址
        pictureUploadDto.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return pictureUploadDto;
    }

    /**
     * 封装原图返回结果
     *
     * @param originFilename 文件名
     * @param file           文件
     * @param uploadPath     上传路径
     * @param imageInfo      图片信息对象
     * @return UploadPictureDto
     * @author Ma Chengrui
     * @since 2025/7/21
     */
    private PictureUploadDto buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round((double) picWidth / picHeight, 2).doubleValue();
        // 封装返回结果
        PictureUploadDto pictureUploadDto = new PictureUploadDto();
        pictureUploadDto.setName(FileUtil.mainName(originFilename));
        pictureUploadDto.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        pictureUploadDto.setPicSize(FileUtil.size(file));
        pictureUploadDto.setPicWidth(picWidth);
        pictureUploadDto.setPicHeight(picHeight);
        pictureUploadDto.setPicScale(picScale);
        pictureUploadDto.setPicFormat(imageInfo.getFormat());
        // Ave是图片主色调
        pictureUploadDto.setPicColor(imageInfo.getAve());
        return pictureUploadDto;
    }

    /**
     * 删除临时文件
     *
     * @param file 文件
     * @author Ma Chengrui
     * @since 2025/7/21
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        boolean delete = file.delete();
        if (!delete) {
            log.error("删除临时文件失败, filePath:{}", file.getAbsolutePath());
        }
    }


}
